// 使用组件
layui.use(['layer', 'table'], function(){
  var layer = layui.layer;
  var table = layui.table;

  //加载数据
  table.render({
      elem: '#accountList'
      , url: 'account/list/' //数据接口
      , headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
      , page: {
          layout: ['count', 'prev', 'page', 'next', 'skip']
          , prev: '上一页'
          , next: '下一页'
          , limit: 10
      }
      , request: {
          pageName: 'pageNum' //页码的参数名称，默认：page
          , limitName: 'pageSize' //每页数据量的参数名，默认：limit
      }
      , parseData: function (res) { //res 即为原始返回的数据
          return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "count": res.data.total,
              "data": res.data.list, //解析数据列表
          };
      }
      , done: function (res, curr, count) {
          // 解决无数据table样式错乱
          if(count == 0){
              $("th[data-key='1-0-6']").css("border-right", "0");
          }
      }
      , cols: [[ //表头
          {type: 'checkbox'}
          , {field: 'username', title: '账号'}
          , {field: 'nickName', title: '昵称'}
          , {field: 'email', title: '邮箱'}
          , {field: 'registerTime', width: 170, title: '注册时间'}
          , {field: 'lastOnlineTime', width: 170, title: '最后在线时间'}
          , {
              field: 'status', title: '状态', width: 80, templet: function (d) {
                  var html = '';
                  switch(d.status) {
                      case 1:
                          html = '<span style="color:#5FB878">正常</span>';
                          break;
                      case 2:
                          html = '<span style="color:#FFB800">锁定</span>';
                          break;
                      case 3:
                          html = '<span style="color:#FF5722">禁用</span>';
                          break;
                      default:
                          html = '<span style="color:#1E9FFF">未知</span>';
                  }
                  return html;
              }
          }
          , {title: '操作', width: 170, toolbar: '#operates', fixed: 'right'}
      ]]
  });

  //监听工具条
  table.on('tool(accountList)', function (obj) {
      var data = obj.data;
      var layEvent = obj.event;
      if (layEvent === 'enable') { //启用
        $.ajax({
            type: "POST",
            url: "account/enable/" + data.id,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    layer.msg('操作成功', {icon: 6});
                    //同步更新缓存对应的值
                    obj.update({status: result.data});
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
      } else if (layEvent === 'reset') { //重置
          layer.confirm('确认重置账号密码吗？', function(index){
              layer.close(index);
              $.ajax({
                  type: "POST",
                  url: "account/password/" + data.id,
                  dataType: "json",
                  headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                  success: function (result) {
                      if (result.code == 0) {
                          layer.msg('操作成功', {icon: 6});
                          //同步更新缓存对应的值
                          obj.update({status: result.data});
                      } else {
                          layer.msg(result.msg, {icon: 5});
                      }
                  }
              });
          });
      }
  });

  $("#search").click(function(){
      var name = $("#searchName").val();
      table.reload('accountList', {page: {curr: 1}, where: {"name": name}});
  });

  $("#noticeAll").click(function(){
    var checkStatus = table.checkStatus('accountList');
    if (checkStatus.data.length === 0) {
        layer.msg('请选择用户');
        return false;
    }
    var width = (windowWidth > 800? 800 : windowWidth) - 40 + 'px';
    parent.layer.prompt({
      formType: 2,
      placeholder: '请输入邮件内容',
      title: '发送邮件通知',
      area: [width, '350px'] //自定义文本域宽高
    }, function(value, index, elem){
      parent.layer.close(index);

      var ids = [];
      $.each(checkStatus.data, function (index, item) {
          ids.push(item.id);
      });

      layer.load();
      $.ajax({
          type: "POST",
          url: "account/notice",
          data: JSON.stringify({"ids": ids, "content": value}),
          contentType: 'application/json;charset=utf-8',
          dataType: "json",
          headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
          success: function (result) {
              layer.closeAll('loading');
              if (result.code == 0) {
                  layer.msg('发送成功', {icon: 6});
              } else {
                  layer.msg(result.msg, {icon: 5});
              }
          }
      });
    });
  });

  initSearch("#searchName");
});
